//
//  HRFollowListViewController.m
//  Hear
//
//  Created by mac on 2017/4/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRFollowListViewController.h"
#import "HRBlackListCell.h"
#import "HRFollowListModel.h"
#import "MJRefresh.h"
#import "HRFollowListViewModel.h"
#import "HRDynamicViewController.h"
#import "HRDynamicViewModel.h"
#import "HREnditNickNameView.h"
#import "HRUserViewModel.h"
#import "HRMessageRootSystemCell.h"
#import "HRFMDBDynamicNotifacationTool.h"
#import "HRNewFriendsRequestListViewController.h"

@interface HRFollowListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSMutableArray *contentArray;
@property (nonatomic, assign)NSInteger pIndex;
@property (nonatomic, strong)HRFollowListViewModel *viewModel;
@property(nonatomic, strong)HRDynamicViewModel *followViewModel;
@property(nonatomic, strong)HRUserViewModel *userViewModel;
@property(nonatomic, assign)BOOL isNewFriendRequestmMessage;

@end

@implementation HRFollowListViewController
#pragma mark - Get and Set
- (HRUserViewModel *)userViewModel{
    if (_userViewModel == nil) {
        _userViewModel = [[HRUserViewModel alloc] init];
    }
    return _userViewModel;
}


-(HRDynamicViewModel *)followViewModel
{
    if (_followViewModel == nil)
    {
        _followViewModel = [HRDynamicViewModel new];
    }
    return _followViewModel;
}


-(HRFollowListViewModel *)viewModel{
    if (_viewModel == nil){
        _viewModel = [HRFollowListViewModel new];
    }
    return _viewModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.title = @"好友列表";
    self.title = @"关注列表";
    self.view.backgroundColor = [UIColor whiteColor];
    self.contentArray = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(clickMenu) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newFirendsNotifi) name:@"newFirendsNotifi" object:nil];

}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
//    return 2;
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section ==0){
//        return 60;
//    }else{
//        return 70;
//    }
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (section == 0){
//        return 1;
//    }else{
        return self.contentArray.count;
//    }
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section == 0){
//        HRMessageRootSystemCell *cell = [HRMessageRootSystemCell cellWithTableView:tableView];
//        cell.iconImageView.image = [UIImage imageNamed:@"新朋友"];
//        cell.typeLabel.text = @"新朋友";
//        cell.unreadCount = self.isNewFriendRequestmMessage;
//        return cell;
//    }else{
        HRBlackListCell *cell = [HRBlackListCell cellWithTableView:tableView];
        
        HRFollowListModel *model = self.contentArray[indexPath.row];
        if (model)
        {
            cell.followListModel = model;
        }
        //取消cell的点击状态
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
//    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section ==0){
//        HRNewFriendsRequestListViewController *VC = [HRNewFriendsRequestListViewController new];
//        VC.title = @"新朋友";
//        [self.navigationController pushViewController:VC animated:YES];
//    }else{
    
    HRFollowListModel *model = self.contentArray[indexPath.row];
    
    EaseMessageViewController *messgaeVC = [[EaseMessageViewController alloc] initWithConversationChatter:model.FollowedUserLocalId conversationType:EMConversationTypeChat];
    messgaeVC.otherNickNameStr = model.UserRemark.length>0?model.UserRemark:model.NickName;
    messgaeVC.otherIconStr = model.UserPictureBackgroundColor;
    messgaeVC.otherIconName = model.UserPictureName;
    messgaeVC.title = model.UserRemark.length>0?model.UserRemark:model.NickName;
    
//        HRDynamicViewController *dynamicVC = [HRDynamicViewController new];
//        dynamicVC.currentUserID = model.FollowedUserLocalId;
    [self.navigationController pushViewController:messgaeVC animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) return NO;
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) return nil;
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"解除关系"
                                                                       handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//                                                                           DDLog(@"取消关注");
                                                                           [self deleteUserFollowInfo:                                               self.contentArray[indexPath.row] andIndex:indexPath.row];
                                                                       }];
    UITableViewRowAction *rowActionSec = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                            title:@"设置备注"
                                                                          handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                                                                              DDLog(@"设置备注");
                                                                              WeakSelf
                                                                              [HREnditNickNameView showEnditNickNameView:^(NSString *content) {
                                                                                  [weakSelf saveUserRemark:content andModel:self.contentArray[indexPath.row] andIndex:indexPath.row];
                                                                              }];
                                                                          }];
    rowActionSec.backgroundColor = MainColor;
    if (self.followType == FollowToMyType){
        return  @[rowActionSec];
    }else{
        return  @[rowAction,rowActionSec];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kFullWidth, 10)];
    view.backgroundColor = CustomColor(240, 240, 240, 1);
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if (section==0){
        return 0;
//    }else{
//        return 10;
//    }
}

- (void)deleteUserFollowInfo:(HRFollowListModel *)model andIndex:(NSInteger)index{
    WeakSelf
    [self.followViewModel deleteUserFollow:@{@"CurrentUserLocalId":USERID,@"FollowedUserLocalId":model.FollowedUserLocalId} isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.deleteCountBlock){
                    weakSelf.deleteCountBlock();
                }
                [MBProgressHUD showMessage:@"已解除关系" finishBlock:nil];
                [weakSelf.contentArray removeObjectAtIndex:index];
                [weakSelf.tableView reloadData];
            });
        }
    }];
}

- (void)newFirendsNotifi{
    self.isNewFriendRequestmMessage = 1;
}


- (void)saveUserRemark:(NSString *)content andModel:(HRFollowListModel *)model andIndex:(NSInteger)index{
    
    WeakSelf
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"CurrentUserLocalId"] = USERID;
    paramDict[@"RemarkUserLocalId"] = model.FollowedUserLocalId;
    paramDict[@"Remark"] = content;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    [self.userViewModel postSaveUserRemark:paramDict isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            model.UserRemark = content;
            [weakSelf.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}

- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}


//-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return @"取消关注";
//}

//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        // Delete the row from the data source.

//    }
//    
//}



- (void)getContentData{
    self.pIndex = 0;
    
    [self getContentData:YES];
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pIndex = 0;
        [self getContentData:YES];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
    //    //上拉加载
    self.tableView.mj_footer=[MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.pIndex ++;
        [weakSelf getContentData:NO];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)getContentData:(BOOL)isHead{
    HRfollowListRequestModel *requestModel = [HRfollowListRequestModel new];
    requestModel.CurrentUserLocalId	 = USERID;
    requestModel.PageSize  = 10;
    requestModel.PageIndex = self.pIndex;
    WeakSelf
    
    HRFollowListModel *adminModel = [HRFollowListModel new];
    adminModel.FollowedUserLocalId = @"admin";
    adminModel.UserPictureName = ADMINICON;
    adminModel.NickName = @"hearer君";
    adminModel.UserNo = @"100000";
    
    NSString *url = @"";
    if (self.followType == MutualFollowType){
        url = @"UserInfo/Get_GetEachFollowList";
    }else if (self.followType == MyFollowType){
//        url = @"UserInfo/Get_GetUserFollowList";
        url = @"UserInfo/Get_GetUserFollowList_";
    }else if (self.followType == FollowToMyType){
        url = @"UserInfo/Get_GetFansList";
    }
    [self.viewModel getUserFollowList:requestModel andUrl:url andResultArr:^(NSArray *resultArr) {
        if (isHead){
            [weakSelf.contentArray removeAllObjects];
        }
        
        [weakSelf.contentArray addObjectsFromArray:resultArr];
        if (self.contentArray.count){
//            if(isHead){
//                [weakSelf.contentArray insertObject:adminModel atIndex:0];
//            }
        }else{
            [weakSelf.contentArray addObject:adminModel];
        }
        
        [weakSelf.tableView reloadData];
        if (resultArr.count < requestModel.PageSize){
            weakSelf.tableView.mj_footer.hidden = YES;
        }else{
            
            weakSelf.tableView.mj_footer.hidden = NO;
        }
        

        
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"cacheTime"];
    [super viewWillAppear:animated];
    self.isNewFriendRequestmMessage = [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"10"]];
    [self getContentData];


}
-(void)viewWillDisappear:(BOOL)animated{
    [[NSUserDefaults standardUserDefaults] setInteger:300 forKey:@"cacheTime"];
}

- (void)clickMenu{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
